<template>
    <div id="Content-page">
        <Paging :pagData="[{ name: '类目参数', router: '/category-params' }]" />
        <div class="content-main">

            <el-tree v-if="dataSource.length" draggable ref="customTreeRef" style="max-width: 600px" :data="dataSource"
                @nodeDrop="dropEnd" :allow-drop="allowDrop" show-checkbox node-key="_id" default-expand-all
                :expand-on-click-node="false"><template #default="{ node, data }">
                    <span style="flex: 1;" class="flex-between">
                        <span>{{ node.label }}</span>
                        <span class="icon_list">
                            <el-icon @click="plusGroup(node, data)">
                                <FolderAdd />
                            </el-icon>
                            <el-icon v-if="node.level == 1" @click="append(node, data)">
                                <Plus />
                            </el-icon>
                            <el-icon :size="15">
                                <Edit @click="edit(node, data)" />
                            </el-icon>
                            <el-icon @click="remove(node, data)">
                                <Delete />
                            </el-icon>
                        </span>
                    </span>
                </template></el-tree>
            <el-button v-else type="primary" link @click="plusGroup">添加一个</el-button>
        </div>

    </div>
    <el-dialog v-model="groupData.visible" :title="groupData.title" width="30%">
        <el-form @submit.native.prevent ref="ruleFormRef" :rules="rules" :model="groupData">
            <el-form-item prop="content">
                <el-input ref="groupInputRef" v-model="groupData.content" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="updateGroupData(ruleFormRef)"> 确定</el-button>
                <el-button @click="groupData.visible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
// 顶部导航组件
import Paging from "@/page/component/Paging-component.vue";
import { ref, onMounted, reactive } from "vue";
import { Plus, Edit, FolderAdd, Delete } from '@element-plus/icons-vue'
import request from "@/api/request.js";
import { ElMessageBox, ElMessage } from "element-plus";
const ruleFormRef = ref();
const groupInputRef = ref();
const customTreeRef = ref();
const groupData = reactive({
    visible: false, title: "", content: "", type: -1, //0为同级，1为新增下级，2为编辑 
    data: {}, node: {}
})
const rules = reactive({
    content: [{ required: true, message: "内容不能为空", trigger: "blur" }]
});
const dataSource = ref([])
// 表格数据
onMounted(() => {
    request.get("/getSkuParams").then(res => {
        dataSource.value = res.data;
        console.log(res);
    })
})
const updateGroupData = (formEl) => {
    formEl.validate(async (valid, fields) => {
        if (valid) {
            groupData.content = groupData.content.trim();
            let parentId;
            if (groupData.node.level == 1) {
                if (groupData.type === 1) {
                    parentId = groupData.node?.key;
                } else {
                    parentId = null;
                }
            }
            if (groupData.node.level == 2) {
                parentId = groupData.node.parent?.key;
            }

            const newChild = { parentId, label: groupData.content };
            ![0, 1].includes(groupData.type) && (newChild._id = groupData.data._id);
            const { data } = await request.post("/updateSkuParams", newChild)
            // 同级新增
            if (groupData.type === 0) {
                if (groupData.node.level === 2) {
                    customTreeRef.value?.append(data, groupData.node.parent)
                } else {
                    dataSource.value.push(data)
                }

                // 下级新增
            } else if (groupData.type === 1) {
                if (groupData.node.level == 1) {
                    customTreeRef.value?.append(data, groupData.node);
                    groupData.node.expand();
                }
            } else {
                groupData.data.label = groupData.content;
                customTreeRef.value?.updateKeyChildren(customTreeRef.value?.getCurrentNode());
            }
            groupData.type = -1;
            groupData.content = "";
            groupData.visible = false;
        }
    })
}
// 新增同级
const plusGroup = (node, data) => {
    ruleFormRef.value?.resetFields();
    groupData.type = 0;
    groupData.visible = true;
    groupData.title = "同级新增";
    groupData.node = node;
    groupData.data = data;
    setTimeout(() => {
        groupInputRef.value.focus();
    }, 200);
};
// 下级新增
const append = (node, data) => {
    ruleFormRef.value?.resetFields();
    groupData.type = 1;
    groupData.visible = true;
    groupData.title = "下级新增";
    groupData.node = node;
    groupData.data = data;
    setTimeout(() => {
        groupInputRef.value.focus();
    }, 200);
}

const remove = (node, data) => {
    console.log(node, data);
    if (data.children?.length) {
        ElMessage.error("子级存在不允许删除")
    } else {
        ElMessageBox.confirm("确实删除？", {
            distinguishCancelAndClose: true
        }).then(() => {
            customTreeRef.value?.remove(node);
            request.delete("delSkuParams/" + node.key);
        })
    }
}

const edit = (node, data) => {
    ruleFormRef.value?.resetFields();
    groupData.type = 2;
    groupData.visible = true;
    groupData.title = "编辑";
    groupData.data = data;
    groupData.node = node;
    groupData.content = data.label;
    setTimeout(() => {
        groupInputRef.value.focus();
    }, 200);

}

// 判断节点存放的位置
const allowDrop = (draggingNode, dropNode, type) => {
    return draggingNode.level === dropNode.level && type !== "inner";
};

const dropEnd = async (beforeNode, afterNode) => {
    console.log("拖拽前后的节点", beforeNode, afterNode);
    await request.post("/exSortSkuParams", { _id1: beforeNode.key, _id2: afterNode.key })
};
</script>

<style>
.icon_list .el-icon {
    padding: 5px;
}
</style>